package com.example.springbootsecurityjwt.domain;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @program: SpringBoot-Security-JWT
 * @description: UserDetails实现类
 * @author: Coder_Pan
 * @create: 2022-03-22 09:33
 **/
@Data
@NoArgsConstructor

public class LoginUser implements Serializable, UserDetails {

    /**
     * 注入User实体，用于后期封装
     */
    private User user;

    /**
     * 存储权限信息
     */
    private List<String> permissions;

    /**
     * 存储SpringSecurity所需要的权限信息的集合
     * @JSONField(serialize = false)  ==>  屏蔽序列化操作
     *
     * SimpleGrantedAuthority ==>  这个类型存入Redis中会报错
     */
    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authorities;


    public LoginUser(User user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }

    /**
     * 获取权限信息
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //将permission中String类型的权限信息封装成SimpleGrantedAuthority对象
        //第一种方式，通过遍历,使用Set集合进行去重
        //        authorities = new HashSet<>();
        //        for (String permission : permissions) {
        //            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(permission);
        //            resList.add(simpleGrantedAuthority);
        //        }
        //        return authorities;
        //第二种方式，通过stream流
        if (authorities != null) {
            //如果权限集合不为空的话，直接返回权限列表，优化代码
            return authorities;
        }
        authorities = permissions.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        return authorities;
    }

    /**
     *
     * @return 密码
     */
    @Override
    public String getPassword() {
        return user.getPassword();
    }

    /**
     *
     * @return 用户名
     */
    @Override
    public String getUsername() {
        return user.getUserName();
    }

    /**
     * 判断是否没过期
     * @return
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 用户状态是否可用
     * @return
     */
    @Override
    public boolean isEnabled() {
        return true;
    }
}
